/******************************************************************************
 * @File name   :      MaintainActivateController.java
 *
 * @Author      :      ANMA
 *
 * @Date        :      Jul 31, 2015
 *
 * @Copyright Notice: 
 * Copyright (c) 2014 DMS, Inc. All  Rights Reserved.
 * This software is published under the terms of the DMS Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * ----------------------------------------------------------------------------
 * Date                         Who         Version         Comments
 * Jul 31, 2015 2:06:59 PM    ANMA      1.0            Initial Version
 *****************************************************************************/
package com.cap.bts.crmdp.dealer.mars.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.cap.bts.commonfunc.common.util.UserUtil;
import com.cap.bts.crmdp.dealer.activation.dto.ActivationQueryDto;
import com.cap.bts.crmdp.dealer.activation.dto.ActivationResultsDto;
import com.cap.bts.crmdp.dealer.activation.dto.CardDto;
import com.cap.bts.crmdp.dealer.coupon.domain.CouponRedeem;
import com.cap.bts.crmdp.dealer.coupon.domain.Eligibility;
import com.cap.bts.crmdp.dealer.coupon.domain.TicketLine;
import com.cap.bts.crmdp.dealer.coupon.dto.CouponForMARSDto;
import com.cap.bts.crmdp.dealer.coupon.service.ICouponBatchService;
import com.cap.bts.crmdp.dealer.coupon.service.ITicKetDefineService;
import com.cap.bts.crmdp.dealer.mars.constants.MARSConstants;
import com.cap.bts.crmdp.dealer.mars.domain.MarsConfig;
import com.cap.bts.crmdp.dealer.mars.domain.MarsLog;
import com.cap.bts.crmdp.dealer.mars.dto.AjaxResponse;
import com.cap.bts.crmdp.dealer.mars.dto.CouponRedeemtionDto;
import com.cap.bts.crmdp.dealer.mars.dto.ItemTypeInfoDto;
import com.cap.bts.crmdp.dealer.mars.dto.MARSParamDto;
import com.cap.bts.crmdp.dealer.mars.dto.PackageMarsListDto;
import com.cap.bts.crmdp.dealer.mars.service.IDataConversionLogService;
import com.cap.bts.crmdp.dealer.mars.service.IMarsActivationService;
import com.cap.bts.crmdp.dealer.mars.service.IMarsCardInventoryService;
import com.cap.bts.crmdp.dealer.mars.service.IMarsConfigService;
import com.cap.bts.crmdp.dealer.mars.service.IMarsLogService;
import com.cap.bts.crmdp.dealer.mars.service.IMarsMaintainCarPlateService;
import com.cap.bts.crmdp.dealer.mars.service.IMarsMaintainMemberService;
import com.cap.bts.crmdp.dealer.mars.service.IMarsMemberPackageService;
import com.cap.bts.crmdp.dealer.mars.service.IMarsPackageDefinitionService;
import com.cap.bts.crmdp.dealer.mars.service.IMarsPurchasePackageService;
import com.cap.bts.crmdp.dealer.mars.service.IMarsRedemptionService;
import com.cap.bts.crmdp.dealer.mars.util.Base64Util;
import com.cap.bts.crmdp.dealer.mars.util.PageBean;
import com.cap.bts.crmdp.dealer.member.domain.CarPlateInfo;
import com.cap.bts.crmdp.dealer.member.domain.MemberInfo;
import com.cap.bts.crmdp.dealer.member.dto.MemberResultsDto;
import com.cap.bts.crmdp.dealer.purchase.constants.PurchaseConstants;
import com.cap.bts.crmdp.dealer.purchase.domain.CardInventory;
import com.cap.bts.crmdp.dealer.purchase.domain.MemberPackageInfo;
import com.cap.bts.crmdp.dealer.purchase.dto.MemberPackageInfoSubmitDto;
import com.cap.bts.crmdp.dealer.redemption.dto.MemberPackageInfoResultsDto;
import com.cap.bts.crmdp.dealer.redemption.dto.MemberQueryDto;
import com.cap.bts.crmdp.mars.util.LogTask;
import com.cap.bts.crmdp.mars.util.ThreadPoolUtil;
import com.cap.bts.crmdp.mars.util.URLEncoderUtil;
import com.cap.bts.crmdp.webservice.CrmFacade;
import com.cap.bts.crmdp.webservice.dto.WSCrmActivationDto;
import com.cap.bts.crmdp.webservice.dto.WSCrmCustomerDto;
import com.cap.bts.crmdp.webservice.dto.WSCrmPackageSellDto;
import com.cap.bts.crmdp.webservice.dto.WSCrmRedemptionDto;
import com.cap.bts.framework.common.controller.BaseController;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.common.util.CookieUtils;
import com.cap.bts.framework.common.util.Pager;
import com.cap.bts.framework.usermgnt.domain.User;

/**
 * 
 */
@Controller
public class MARSController extends BaseController {
    private static final Logger LOGGER = Logger.getLogger(MARSController.class);
    
    private static final String SUCCESS = "success";
    private static final String REDIRECT = "redirect:";
    private static final String RESULT = "result";
    private static final String ERROR_MSG = "errorMsg";
    private static final String ERROR = "error";

    @Autowired
    IMarsActivationService activationService;

    @Autowired
    IMarsMaintainCarPlateService maintainCarPlateService;

    @Autowired
    IMarsMaintainMemberService maintainMemberService;

    @Autowired
    IMarsLogService marsLogService;
    @Autowired
    IDataConversionLogService dataConversionLogServiceImpl;

    @Autowired
    IMarsRedemptionService redemptionService;

    @Autowired
    IMarsMemberPackageService memberPackageService;

    @Autowired
    IMarsCardInventoryService cardInventoryService;

    @Autowired
    IMarsPurchasePackageService purchasePackageService;

    @Autowired
    IMarsPackageDefinitionService packageDefinitionService;
    
    @Autowired
    private ICouponBatchService couponBatchServiceImpl;
    @Autowired
    private ITicKetDefineService ticKetDefineServiceImpl;
    @Autowired
    private IMarsConfigService marsConfigServiceImpl;
    

    @RequestMapping(value = "/MARS")
    public String singlePageMARS(String p, HttpServletRequest request, HttpServletResponse response) {
        MarsLog marsLog = new MarsLog("page");
        marsLog.setSuccessFlag(SUCCESS);
        marsLog.setParamTextEncrypt(p);
        LOGGER.info("receive: " + p);

        StringBuilder urlBuilder = new StringBuilder();
        HttpSession session = request.getSession();
        try {
            String xmlText = Base64Util.decode(p);

            marsLog.setParamText(xmlText);

            LOGGER.info("Decrypting information: " + xmlText);

            MARSParamDto dto = buildParamFromXml(xmlText);
            
            //todo 合法性校验
			MarsConfig config = marsConfigServiceImpl.get();
			
			if(config == null){
				throw new AppException("ERROR", "MARS接口相关信息未配置，请联系管理员！");
			}
			
			
			LOGGER.info("into MARS SESSION: " + session.getId());
			if(!org.apache.commons.lang3.StringUtils.equalsIgnoreCase(config.getToken(), dto.getToken())){
				throw new AppException("403", "未授权非法访问！");
			}else{
				//session 中注入标识
				session.setAttribute("AUTHORIZE_MARS", true);
				MARSConstants.MARS_SESSSION_ID_LIST.add(session.getId());
				
				if(MARSConstants.MARS_SESSSION_ID_LIST.size() > 10000){
					while(MARSConstants.MARS_SESSSION_ID_LIST.size() > 10000){
						MARSConstants.MARS_SESSSION_ID_LIST.remove(0);
					}
				}
				
				LOGGER.info("init MARS SESSION: " + session.getId());
			}
            
            

            String method = dto.getMethod();
            marsLog.setCallMethod(method);

            if ("PACKAGE_USE_DETAIL".equals(method)) {
                // 先同步客户&车辆信息
                syncCustomer(dto);

                urlBuilder.append(REDIRECT).append(MARSConstants.MARS_PACKAE_USE_DETAIL_URL);
                urlBuilder.append(";jsessionid=").append(session.getId());
                urlBuilder.append("?dealerId=")
                    .append(URLEncoderUtil.encode(dto.getServerCenter()));
                urlBuilder.append("&marsMemberId=").append(
                    URLEncoderUtil.encode(dto.getCustomerId()));
                urlBuilder.append("&carMarsId=").append(URLEncoderUtil.encode(dto.getCarPlate()));
                urlBuilder.append("&_d=").append(System.currentTimeMillis());

            } else if ("SELL".equals(method)) {
                // 先同步客户&车辆信息
                syncCustomer(dto);

                urlBuilder.append(REDIRECT).append(MARSConstants.MARS_SELL_PACKAGE_URL);
                urlBuilder.append(";jsessionid=").append(session.getId());
                urlBuilder.append("?customerId=")
                    .append(URLEncoderUtil.encode(dto.getCustomerId()));
                urlBuilder.append("&mobilePhone=").append(
                    URLEncoderUtil.encode(dto.getMobilePhone()));
                urlBuilder.append("&customerName=").append(
                    URLEncoderUtil.encode(dto.getCustomerName()));
                urlBuilder.append("&carId=").append(URLEncoderUtil.encode(dto.getCarId()));
                urlBuilder.append("&carPlate=").append(URLEncoderUtil.encode(dto.getCarPlate()));
                urlBuilder.append("&soNumber=").append(URLEncoderUtil.encode(dto.getSoNumber()));
                urlBuilder.append("&serverCenter=").append(
                    URLEncoderUtil.encode(dto.getServerCenter()));
                urlBuilder.append("&_d=").append(System.currentTimeMillis());

            } else if ("ACTIVATION".equals(method)) {
                // 先同步客户&车辆信息
                syncCustomer(dto);

                urlBuilder.append(REDIRECT).append(MARSConstants.MARS_ACTIVATION_URL);
                urlBuilder.append(";jsessionid=").append(session.getId());
                urlBuilder.append("?customerId=")
                    .append(URLEncoderUtil.encode(dto.getCustomerId()));
                urlBuilder.append("&mobilePhone=").append(
                    URLEncoderUtil.encode(dto.getMobilePhone()));
                urlBuilder.append("&customerName=").append(
                    URLEncoderUtil.encode(dto.getCustomerName()));
                urlBuilder.append("&carId=").append(URLEncoderUtil.encode(dto.getCarId()));
                urlBuilder.append("&carPlate=").append(URLEncoderUtil.encode(dto.getCarPlate()));
                urlBuilder.append("&soNumber=").append(URLEncoderUtil.encode(dto.getSoNumber()));
                for (String cardNumber : dto.getCardNumbers()) {
                    urlBuilder.append("&cardNumber=").append(cardNumber);
                }

                urlBuilder.append("&serverCenter=").append(
                    URLEncoderUtil.encode(dto.getServerCenter()));
                urlBuilder.append("&_d=").append(System.currentTimeMillis());

            } else if ("REDEMPTION".equals(method)) {
                // 先同步客户&车辆信息
                syncCustomer(dto);

                urlBuilder.append(REDIRECT).append(MARSConstants.MARS_REDEMPTION_URL);
                urlBuilder.append(";jsessionid=").append(session.getId());
                urlBuilder.append("?customerId=").append(URLEncoderUtil.encode(dto.getCustomerId()));
                urlBuilder.append("&mobilePhone=").append(URLEncoderUtil.encode(dto.getMobilePhone()));
                urlBuilder.append("&customerName=").append(URLEncoderUtil.encode(dto.getCustomerName()));
                urlBuilder.append("&carId=").append(URLEncoderUtil.encode(dto.getCarId()));
                urlBuilder.append("&carPlate=").append(URLEncoderUtil.encode(dto.getCarPlate()));
                urlBuilder.append("&soNumber=").append(URLEncoderUtil.encode(dto.getSoNumber()));
                urlBuilder.append("&serverCenter=").append(URLEncoderUtil.encode(dto.getServerCenter()));
                urlBuilder.append("&_d=").append(System.currentTimeMillis());

            }else if ("REPORT".equals(method)) {
                // 先同步客户&车辆信息
//                syncCustomer(dto);

                urlBuilder.append(REDIRECT).append(MARSConstants.MARS_REPORT_URL);
                urlBuilder.append(";jsessionid=").append(session.getId());
                urlBuilder.append("?dealerId=").append(URLEncoderUtil.encode(dto.getServerCenter()));
                urlBuilder.append("&fromMars=").append(System.currentTimeMillis());
                urlBuilder.append("&_d=").append(System.currentTimeMillis());

            }else if ("RECEIVE".equals(method)) {
                // 先同步客户&车辆信息
//                syncCustomer(dto);

                urlBuilder.append(REDIRECT).append(MARSConstants.MARS_RECEIVE_AND_SELECT_PACKAGE);
                urlBuilder.append(";jsessionid=").append(session.getId());
                urlBuilder.append("?dealerId=").append(URLEncoderUtil.encode(dto.getServerCenter()));
                urlBuilder.append("&_d=").append(System.currentTimeMillis());

            }else if ("SMS".equals(method)) {
            	User user = new User();
                user.setId(0L);
                user.setDealerId(Long.valueOf(dto.getServerCenter()));
                UserUtil.setMarsCurrentUser(user);

              urlBuilder.append(REDIRECT).append(MARSConstants.MARS_SMS_URL);
              urlBuilder.append(";jsessionid=").append(session.getId());
              urlBuilder.append("?dealerNum=").append(URLEncoderUtil.encode(dto.getServerCenter()));
              urlBuilder.append("&_d=").append(System.currentTimeMillis());

            }else if ("COUPONREDEMPT".equals(method)) {
            	// 先同步客户&车辆信息
                syncCustomer(dto);
	        	
	        	urlBuilder.append(REDIRECT).append(MARSConstants.MARS_COUPONREDEMPT_URL);
                urlBuilder.append(";jsessionid=").append(session.getId());
	        	urlBuilder.append("?customerId=").append(URLEncoderUtil.encode(dto.getCustomerId()));
                urlBuilder.append("&mobilePhone=").append(URLEncoderUtil.encode(dto.getMobilePhone()));
                urlBuilder.append("&customerName=").append(URLEncoderUtil.encode(dto.getCustomerName()));
                urlBuilder.append("&carId=").append(URLEncoderUtil.encode(dto.getCarId()));
                urlBuilder.append("&carPlate=").append(URLEncoderUtil.encode(dto.getCarPlate()));
                urlBuilder.append("&soNumber=").append(URLEncoderUtil.encode(dto.getSoNumber()));
                urlBuilder.append("&serverCenter=").append(URLEncoderUtil.encode(dto.getServerCenter()));
                urlBuilder.append("&_d=").append(System.currentTimeMillis());
        	
            }else{
            	urlBuilder.append("/mars/marsError");
                marsLog.setSuccessFlag("failure");
                marsLog.setDescp("method 缺失");
            }

        } catch (Exception e) {
            LOGGER.error("", e);
            urlBuilder.append("/mars/marsError");
            marsLog.setSuccessFlag("failure");
            marsLog.setDescp(e.getMessage());
        }

        marsLog.setReturnText(urlBuilder.toString());
        ThreadPoolUtil.execute(new LogTask(marsLog));
        
        String sessionId = session.getId();
        String requestSessionId = null;
        Cookie[] Cookies = request.getCookies();

        if(Cookies != null){
            for (Cookie cookie : Cookies) {
                String name = cookie.getName();
                if("jsessionid".equalsIgnoreCase(name)){
                	requestSessionId = cookie.getValue();
                }
            }
        }

        if(!StringUtils.equalsIgnoreCase(requestSessionId, sessionId)){
            response.addHeader("Set-Cookie", "JSESSIONID=" + sessionId + "; path=/; HttpOnly");
        }

        return urlBuilder.toString();
    }

    @RequestMapping(value = "/logMars")
    public String log() {

        return "/mars/log";
    }

    @RequestMapping(value = "/logMars/data")
    @ResponseBody
    public Object logData(Pager pager) {
        return marsLogService.queryPage(pager, true);
    }
    
    
    @RequestMapping(value = "/logDataConversion")
    public String logDataConversion() {

        return "/mars/log2";
    }

    @RequestMapping(value = "/logDataConversion/data")
    @ResponseBody
    public Object logDataDataConversion(Pager pager) {
    	
        return dataConversionLogServiceImpl.queryPage(pager);
    }

    private MARSParamDto buildParamFromXml(String xmlText) {
        MARSParamDto dto = new MARSParamDto();

        Document document = null;
        try {
            document = DocumentHelper.parseText(xmlText);
        } catch (DocumentException e) {
            LOGGER.error("", e);
        }
        Element rootElement = document.getRootElement();

        dto.setToken(getNodeValue(rootElement, "token"));
        dto.setMethod(getNodeValue(rootElement, "method"));
        dto.setCustomerId(getNodeValue(rootElement, "customerId"));
        dto.setCustomerName(getNodeValue(rootElement, "customerName"));
        dto.setMobilePhone(getNodeValue(rootElement, "mobilePhone"));
        dto.setSoNumber(getNodeValue(rootElement, "soNumber"));
        dto.setCarId(getNodeValue(rootElement, "carId"));
        dto.setCarPlate(getNodeValue(rootElement, "carPlate"));
        dto.setServerCenter(getNodeValue(rootElement, "serverCenter"));

        List<Node> cardNumberNodes = rootElement.selectNodes("cards/cardNumber");
        if (cardNumberNodes != null) {
            for (Node node : cardNumberNodes) {
                dto.getCardNumbers().add(getNodeValue(node));
            }
        }

        return dto;
    }

    private void syncCustomer(MARSParamDto dto) throws AppException {
    	
    	if(org.apache.commons.lang3.StringUtils.isBlank(dto.getCustomerId())
    			|| org.apache.commons.lang3.StringUtils.isBlank(dto.getServerCenter())
    			|| org.apache.commons.lang3.StringUtils.isBlank(dto.getMobilePhone())
    			|| (org.apache.commons.lang3.StringUtils.isNotBlank(dto.getCarId()) 
    					&& org.apache.commons.lang3.StringUtils.isBlank(dto.getCarPlate()))
    			){
    		throw new AppException("ERROR", "必要参数缺失");
    	}
    	
    	
        // 先同步客户&车辆信息
        WSCrmCustomerDto customerSyncdto = new WSCrmCustomerDto(true);

        customerSyncdto.setCustomerId(dto.getCustomerId());
        customerSyncdto.setCustomerName(dto.getCustomerName());
        customerSyncdto.setMobilePhone(dto.getMobilePhone());
        customerSyncdto.setCarPlate(dto.getCarPlate());
        customerSyncdto.setCarId(dto.getCarId());
        customerSyncdto.setServerCenter(dto.getServerCenter());

        new CrmFacade().processCustomerInfo(customerSyncdto);
    }

    private String getNodeValue(Node rootElement, String select) {
        Node node = rootElement.selectSingleNode(select);
        if (node != null) {
            String val = node.getText();
            return val == null ? "" : val;
        }

        return "";
    }

    private String getNodeValue(Node node) {
        if (node != null) {
            return node.getText();
        }

        return null;
    }

    @RequestMapping(value = "/MARS/toMemberPurchaseMars")
    public String toMemberPurchaseMars(WSCrmPackageSellDto wsdto, Model model,
        HttpServletRequest request) throws AppException {
        MemberResultsDto dto = new MemberResultsDto();
        if (wsdto != null) {
        	/*
    		CarPlateInfo carPlateInfo = maintainCarPlateService.getCarPlateInfoByMarsCarId(wsdto.getCarId());
    		if (carPlateInfo != null) {
    			dto.setCarPlate(carPlateInfo.getCarPlate());
    		}
    		*/
            
            dto.setSoNumber(wsdto.getSoNumber());
            // 根据Mars信息查找到CRM中的会员ID传到前台用于购买操作
            MemberInfo memberInfo = maintainMemberService.getMemberByMarsInfo(
                wsdto.getServerCenter(), wsdto.getCustomerId());
            if (memberInfo != null) {
                dto.setId(memberInfo.getId());
                dto.setDealerId(memberInfo.getDealerId());
                dto.setMemberName(memberInfo.getMemberName());
                dto.setMobilePhone(memberInfo.getMobilePhone());
                
				CarPlateInfo carPlateInfo = maintainCarPlateService
						.getCarPlateInfoByMarsCarIdAndMemberId(wsdto.getCarId(), memberInfo.getId());
				if (carPlateInfo != null) {
					dto.setCarPlate(carPlateInfo.getCarPlate());
				}
            }
            
            
            
        }
        model.addAttribute("packageDefinitionListDto",
            packageDefinitionService.getAllPackageDefinitionList(Long.valueOf(wsdto.getServerCenter())));
        model.addAttribute(PurchaseConstants.MEMBER_RESULTS_DTO, dto);
        return "/mars/purchaseMars";
    }

    /**
     * 获取库存信息
     * 
     * @Date : 2015-7-15
     * @param dto
     *            MemberResultsDto
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "/MARS/getPackageInfoMars")
    @ResponseBody
    public String getPackageInfoMars(Long cardDefId, Long dealerId, Model model,
        HttpServletRequest request) throws AppException {
        String quantity = "0";
        CardInventory cardInventory = cardInventoryService
            .getCardInventoryInfo(cardDefId, dealerId);
        if (cardInventory != null) {
            quantity = cardInventory.getOnhandQuantity().toString();
        }
        return quantity;
    }

    /**
     * 检查是否存在该实物卡
     * 
     * @Date : 2015-7-15
     * @param dto
     *            MemberResultsDto
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "/MARS/checkMemberPackageInfoExsitMars")
    @ResponseBody
    public Boolean checkMemberPackageInfoExsit(MemberPackageInfoSubmitDto dto, Model model,
        HttpServletRequest request) throws AppException {
        return memberPackageService.checkMemberPackageExsit(dto);
    }

    /**
     * Mars购买时使用
     * 
     * @Date : 2015-7-15
     * @param dto
     *            MemberPackageInfoSubmitDto
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "/MARS/purchaseMars")
    @ResponseBody
    public Map<String, Object> purchaseMars(MemberPackageInfoSubmitDto dto, Model model,
        HttpServletRequest request) throws AppException {
        User user = new User();
        user.setId(0L);
        user.setDealerId(dto.getDealerId());
        UserUtil.setMarsCurrentUser(user);
        Map<String, Object> rtnMap = new HashMap<String, Object>();
        try {
            dto.setPackageNumber(dto.getPackageNumber().toUpperCase());
            purchasePackageService.purchasePackageMars(dto,true);
        } catch (AppException e) {
            LOGGER.error(e.getMessage(), e);
            UserUtil.removeMarsCurrentUser();
            rtnMap.put(RESULT, false);
            rtnMap.put(ERROR_MSG, e.getMessage());
            return rtnMap;
        }
        UserUtil.removeMarsCurrentUser();
        rtnMap.put(RESULT, true);
        return rtnMap;
    }
    
    @RequestMapping(value = "/MARS/purchaseMarsForRepair")
    @ResponseBody
    public Map<String, Object> purchaseMarsForRepair(MemberPackageInfoSubmitDto dto, Model model,
        HttpServletRequest request) throws AppException {
        User user = new User();
        user.setId(0L);
        user.setDealerId(dto.getDealerId());
        UserUtil.setMarsCurrentUser(user);
        Map<String, Object> rtnMap = new HashMap<String, Object>();
        try {
            dto.setPackageNumber(dto.getPackageNumber().toUpperCase());
            purchasePackageService.purchasePackageMars(dto,false);
        } catch (AppException e) {
            LOGGER.error(e.getMessage(), e);
            UserUtil.removeMarsCurrentUser();
            rtnMap.put(RESULT, false);
            rtnMap.put(ERROR_MSG, e.getMessage());
            return rtnMap;
        }
        UserUtil.removeMarsCurrentUser();
        rtnMap.put(RESULT, true);
        return rtnMap;
    }

    /**
     * 
     * @Date : 2015-7-20
     * @param MemberResultsDto
     *            String
     * @param model
     *            Model
     * @param request
     *            HttpServletRequest
     * @return String
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/MARS/isPackageNumberExist")
    public Map<String, Object> isPackageNumberExist(MemberResultsDto dto, Model model,
        HttpServletRequest request) throws AppException {
        Map<String, Object> rtnMap = new HashMap<String, Object>();
        ActivationQueryDto aqd = new ActivationQueryDto();
        aqd.setPackageNumber(dto.getPackageNumber());
        MemberPackageInfo cmpi = null;
        if (dto.getPackageNumber() != null && !"".equals(dto.getPackageNumber())) {
            cmpi = activationService.checkPackageNumberByActivationDto(aqd);
            if (cmpi == null) {
                rtnMap.put(ERROR, "该卡号不存在!");
                rtnMap.put(SUCCESS, false);
            } else {
                if (cmpi.getPurchaseDate() != null) {
                    rtnMap.put(SUCCESS, true);
                } else {
                    rtnMap.put(ERROR, "该卡号尚未购买!");
                    rtnMap.put(SUCCESS, false);
                }
            }

        } else {
            rtnMap.put(ERROR, "卡号不能为空!");
            rtnMap.put(SUCCESS, false);
        }

        return rtnMap;
    }

    /**
     * 
     * @Date : 2015-7-20
     * @param dto
     *            MemberResultsDto
     * @param model
     *            Model
     * @param request
     *            HttpServletRequest
     * @throws AppException
     */
    @RequestMapping(value = "/MARS/toPurchaseDetailInfo")
    public String toPurchaseDetailInfo(String packageNumber, Model model, HttpServletRequest request)
        throws AppException {
        ActivationQueryDto aqd = new ActivationQueryDto();
        aqd.setPackageNumber(packageNumber);
        MemberPackageInfo cmpi = activationService.checkPackageNumberByActivationDto(aqd);
        MemberInfo mi = null;
        CarPlateInfo cpi = null;
        if (cmpi != null) {
            aqd.setPrice(cmpi.getActualPrice());
            aqd.setPurchaseDate(cmpi.getPurchaseDate());
            if (cmpi.getActiveDate() != null) {
                aqd.setIsActived(true);
            } else {
                aqd.setIsActived(false);
            }
            aqd.setPackageName(cmpi.getPackageDefinition().getName());
            aqd.setCardName(cmpi.getCardDefinition().getName());
            mi = maintainMemberService.getMemberById(cmpi.getMemberId());
            cpi = maintainCarPlateService.getCarPlateInfoById(cmpi.getCarId());
        }
        if (mi != null) {
            aqd.setMemberName(mi.getMemberName());
            aqd.setMobilePhone(mi.getMobilePhone());
        }
        if (cpi != null) {
            aqd.setCarPlate(cpi.getCarPlate());
        }

        aqd.setPackageNumber(packageNumber);
        model.addAttribute("dto", aqd);

        return "/mars/purchaseDetailInfo";
    }

    /**
     * 
     * @Date : 2015-7-20
     * @param dto
     *            MemberResultsDto
     * @param model
     *            Model
     * @param request
     *            HttpServletRequest
     * @return String
     * @throws UnsupportedEncodingException
     * @throws Exception
     */
    @RequestMapping(value = "/MARS/toMemberActivationMars")
    public String toMemberActivationMars(WSCrmActivationDto wsdto, Model model,
        HttpServletRequest request) throws AppException {
        ActivationResultsDto activationResultsDto = new ActivationResultsDto();
        
		/*
		CarPlateInfo carPlateInfo = maintainCarPlateService.getCarPlateInfoByMarsCarId(wsdto.getCarId());
		if (carPlateInfo != null) {
			activationResultsDto.setCarPlate(carPlateInfo.getCarPlate());
		}
		*/

        activationResultsDto.setSoNumber(wsdto.getSoNumber());
        // 根据Mars信息查找到CRM中的会员ID传到前台用于购买操作
        MemberInfo memberInfo = maintainMemberService.getMemberByMarsInfo(wsdto.getServerCenter(),
            wsdto.getCustomerId());
        if (memberInfo != null) {
            activationResultsDto.setMemberId(memberInfo.getId());
            activationResultsDto.setDealerId(memberInfo.getDealerId());
            activationResultsDto.setMemberName(memberInfo.getMemberName());
            activationResultsDto.setMobilePhone(memberInfo.getMobilePhone());
        }
        
		CarPlateInfo carPlateInfo = maintainCarPlateService.getCarPlateInfoByMarsCarIdAndMemberId(wsdto.getCarId(),
				memberInfo.getId());
		if (carPlateInfo != null) {
			activationResultsDto.setCarPlate(carPlateInfo.getCarPlate());
		}

        List<CardDto> cardList = new ArrayList<CardDto>();
        if (wsdto.getCardNumber() != null) {
            for (String s : wsdto.getCardNumber()) {
                CardDto cardDto = new CardDto();
                cardDto.setCardNumber(s);
                MemberPackageInfo mpi=memberPackageService.getMemberPackageInfoByPackageNumber(s);
                if(mpi!=null){
                    cardDto.setPackageName(mpi.getPackageDefinition().getName());
                }
                cardList.add(cardDto);
            }
            activationResultsDto.setCardList(cardList);
        }
        activationResultsDto.setMarsCarId(wsdto.getCarId());
        activationResultsDto.setMarsCustomerId(wsdto.getCustomerId());
        model.addAttribute("dto", activationResultsDto);

       
            return "/mars/activationNowMars";
    }

    /**
     * 
     * @Date : 2015-7-20
     * @param dto
     *            ActivationQueryDto
     * @param model
     *            Model
     * @param request
     *            HttpServletRequest
     * @return String
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/MARS/toSaveMemberActivationMars")
    public Map<String, Object> saveMemberActivationMars(MemberPackageInfoSubmitDto dto,
        Model model, HttpServletRequest request) throws AppException {
        User user = new User();
        user.setId(0L);
        user.setDealerId(dto.getDealerId());
        UserUtil.setMarsCurrentUser(user);

        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            resultMap = activationService.packageActivationMars(dto);
        } catch (AppException e) {
            UserUtil.removeMarsCurrentUser();
            LOGGER.error("Mars Error", e);
            resultMap.put(RESULT, false);
            resultMap.put(ERROR_MSG, e.getMessage());
        }
        UserUtil.removeMarsCurrentUser();
        return resultMap;
    }

    /**
     * 
     * @Date : 2015-7-20
     * @param dto
     *            ActivationQueryDto
     * @param model
     *            Model
     * @param request
     *            HttpServletRequest
     * @return String
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/MARS/toSaveMemberActivationListMars")
    public Map<String, Object> saveMemberActivationListMars(MemberPackageInfoSubmitDto dto,
        Model model, HttpServletRequest request) throws AppException {
        User user = new User();
        user.setId(0L);
        user.setDealerId(dto.getDealerId());
        UserUtil.setMarsCurrentUser(user);

        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            resultMap = activationService.packageListActivationMars(dto);
        } catch (AppException e) {
            UserUtil.removeMarsCurrentUser();
            LOGGER.error("Mars Error", e);
            resultMap.put(RESULT, false);
            resultMap.put(ERROR_MSG, e.getMessage());
        }
        UserUtil.removeMarsCurrentUser();
        return resultMap;

    }

    /**
     * 转向使用套餐画面
     * 
     * @Date : 2015-7-22
     * @param model
     *            Model
     * @param request
     *            HttpServletRequest
     * @return String
     * @throws AppException
     */
    @RequestMapping(value = "/MARS/showMemberPackageListMars")
    public String showMemberPackageListMars(WSCrmRedemptionDto wsdto, Model model,
        HttpServletRequest request) throws AppException {
        User user = new User();
        user.setId(0L);
        if(wsdto.getServerCenter()!=null){
            user.setDealerId(Long.valueOf(wsdto.getServerCenter()));
        }
        UserUtil.setMarsCurrentUser(user);
        
        MemberQueryDto dto = new MemberQueryDto();
        
        dto.setSoNumber(wsdto.getSoNumber());
        // 根据Mars信息查找到CRM中的会员ID传到前台用于购买操作
        MemberInfo memberInfo = maintainMemberService.getMemberByMarsInfo(wsdto.getServerCenter(),
            wsdto.getCustomerId());
        if (memberInfo != null) {
            dto.setId(memberInfo.getId());
            dto.setDealerId(memberInfo.getDealerId());
            dto.setMemberName(memberInfo.getMemberName());
            dto.setMobilePhone(memberInfo.getMobilePhone());
        }
        
        CarPlateInfo carPlateInfo = maintainCarPlateService.getCarPlateInfoByMarsCarIdAndMemberId(wsdto.getCarId(),
				memberInfo.getId());
		if (carPlateInfo != null) {
			dto.setCarPlate(carPlateInfo.getCarPlate());
		}
        
        List<MemberPackageInfoResultsDto> list = redemptionService.getPackageListByMemberMars(dto);
        model.addAttribute("memberPackageInfoList", list);
        model.addAttribute("memberInfo", dto);
        
        return "/mars/showMemberPackageListMars";
    }

    /**
     * 检查该会员是否存在激活后的套餐
     * 
     * @Date : 2015-7-22
     * @param model
     *            Model
     * @param request
     *            HttpServletRequest
     * @return String
     * @throws AppException
     */
    @ResponseBody
    @RequestMapping(value = "/MARS/usePackageItem")
    public Map<String, Object> usePackageItem(PackageMarsListDto packageMarsListDto, Model model,
        HttpServletRequest request) throws AppException {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            redemptionService.usePackageItemList(packageMarsListDto);
        } catch (AppException e) {
            LOGGER.error(e.getMessage(), e);
            returnMap.put(RESULT, false);
            returnMap.put(ERROR_MSG, e.getMessage());
            return returnMap;
        }
        returnMap.put(RESULT, true);
        return returnMap;
    }

    /**
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @ResponseBody
    @RequestMapping(value = "/MARS/sendRedemptionCode")
    public boolean sendRedemptionCode(Long redemptionId, Long memberPackageId) throws AppException {
        return redemptionService.sendRedemptionCode(redemptionId, memberPackageId);
    }
    
    /**
     * 
     * @Date        :      Nov 11, 2015
     * @param itemId
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "/MARS/toWecareItemTypeInfoList")
    public String toWecareItemTypeInfoList(ItemTypeInfoDto dto,Model model, HttpServletRequest request) throws AppException{
        int index =1;
        if(dto.getIndex()!=null){
            index=dto.getIndex(); 
        }
        //生成随机字符串
        if(!StringUtils.isNotBlank(dto.getRandomString())){
        	String randomString = RandomStringUtils.randomAlphanumeric(32);
        	dto.setRandomString(randomString);
        }
        List<ItemTypeInfoDto> list = redemptionService.getItemTypeInfoListByItemId(dto); 
        List<ItemTypeInfoDto> pageList= new ArrayList<ItemTypeInfoDto>();
        if(dto.getqItemSource() != null){
        	if(dto.getqItemSource() == 0 || dto.getqItemSource() == 1 ){
        		int i = 0;
        		for (; i < list.size(); i++) {
        			if(!dto.getqItemSource().equals(list.get(i).getItemSource())){
        				list.remove(i);
        				i--;
        			}
        		}
        	}
        }
        
        for(int j = 0;j< list.size(); j++){
            Boolean isResultFlag=true;
            
            if(isResultFlag && dto.getSearchItem() != null && !"".equals(dto.getSearchItem())){
            	//搜索范围
            	String searchString = (list.get(j).getDescription1() + list.get(j).getDescription2()).toUpperCase();
            	String serachStringResult1 = searchString.replaceAll("((?=[\\x21-\\x7e]+)[^A-Za-z0-9])","");
            	String serachStringResult =list.get(j).getItemCode().toUpperCase() + serachStringResult1.replaceAll(" ","");
            	//搜索条件
            	String search = dto.getSearchItem().toUpperCase();
            	//处理通配符
            	String[] searchArray = search.split("\\*");
            	if(searchArray != null && searchArray.length>0){
            		Boolean isResult=true;
            		for(int i=0;i <searchArray.length; i++){
            			if(isResult && !serachStringResult.contains(searchArray[i].replaceAll(" ",""))){
            				isResult=false;
                		}
            		}
            		if(!isResult){
            			isResultFlag=false;
            		}
            	}else{
            		if(!serachStringResult.contains(search.replaceAll(" ",""))){
            			isResultFlag=false;
            		}
            	}
            }
            
            if(isResultFlag){
            	pageList.add(list.get(j));
            }
        }
       

        PageBean page = new PageBean();  
        List<ItemTypeInfoDto> listNew= new ArrayList<ItemTypeInfoDto>();  
        if (pageList != null &&page!=null) {  
            for (int i = (index - 1) * page.getPageSize(); i < index * page.getPageSize()  
                    && i < pageList.size(); i++) {  
                listNew.add(pageList.get(i));  
            }  
            page.setPageTotal((pageList.size() + page.getPageSize() - 1) / page.getPageSize());  
            page.setRowTotal(pageList.size());  
        }  
        page.setCurrentPage(index);  
        page.setList(listNew);  
        
        
        
        model.addAttribute("indexs", index);
        model.addAttribute("page", page);
        model.addAttribute("dto", dto);
        model.addAttribute("itemTypeList", listNew);
        return "/mars/itemTypeInfoList";
    }
    
    
    /**
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    
    @RequestMapping(value = "/MARS/reports")
    public String sendRedemptionCode(Model model, HttpServletRequest request) throws AppException {
    	String flag = request.getParameter("fromMars");
    	if(org.apache.commons.lang.StringUtils.isNotBlank(flag)){
    		request.getSession().setAttribute("FROM_MARS_FLAG", true);
    	}
    	request.getSession().setAttribute("MARS_DEALERID", request.getParameter("dealerId"));
    	return "/mars/reports";
    }
    
    
    @RequestMapping(value = "/MARS/receiveAndSelectPackage")
    public String receiveAndSelectPackage(Model model, HttpServletRequest request) throws AppException {
    	String flag = request.getParameter("dealerId");
    	if(org.apache.commons.lang.StringUtils.isNotBlank(flag)){
    		request.getSession().setAttribute("FROM_MARS_FLAG", true);
    	}
    	request.getSession().setAttribute("MARS_DEALERID", request.getParameter("dealerId"));
    	return "/mars/receiveAndSelectPackage";
    }
    
    

    /**
     * 
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    
    @RequestMapping(value = "/MARS/coupon/redemption")
    @ResponseBody
    public Object redeemCoupon(@RequestBody String jsonStr) throws AppException {
    	AjaxResponse ajaxResponse = new AjaxResponse();
    			
    	
    	CouponRedeemtionDto dto = JSON.parseObject(jsonStr, CouponRedeemtionDto.class);
    	
    	try{
    		couponBatchServiceImpl.couponRedemption(dto, ajaxResponse);
    	}catch(Exception e){
    		ajaxResponse.setSuccess(false);
    		ajaxResponse.setMessage("操作失败：" + e.getMessage());
    	}
    	
    	
    	return ajaxResponse;
    }
    
    
    @RequestMapping(value = "/MARS/couponInfo")
    @ResponseBody
    public Object checkCoupon(@RequestParam("couponNumber")String  couponNumber, HttpServletRequest request) throws AppException {
    	AjaxResponse ajaxResponse = new AjaxResponse();
    	
    	if(org.apache.commons.lang3.StringUtils.isBlank(couponNumber)){
    		ajaxResponse.setSuccess(false);
    		ajaxResponse.setMessage("优惠券“" + couponNumber + "”不存在！");
    	}else{
    		
    		CouponForMARSDto dto = couponBatchServiceImpl.getCouponByCouponNumber(couponNumber);
    		
    		if(dto == null){
    			ajaxResponse.setSuccess(false);
        		ajaxResponse.setMessage("优惠券“" + couponNumber + "”不存在！");	
        		
        		return ajaxResponse;
    		}
    		
    		ajaxResponse.setData(dto);
    		Calendar calendar = Calendar.getInstance();
    		Date now = calendar.getTime();
    		//未开始
    		if(now.before(dto.getStartDate())){

    			ajaxResponse.setSuccess(false);
    			ajaxResponse.setMessage("该优惠券活动尚未开始，将于" + DateFormatUtils.format(dto.getStartDate(), "yyyy-MM-dd")  + "开始启动，敬请期待！");
    		}
    		//日期加1天再判断结束时间，使最后一天可用
    		calendar.add(Calendar.DAY_OF_MONTH, 1);
    		now = calendar.getTime();
    		//已结束
    		if(now.after(dto.getEndDate())){
    			
    			ajaxResponse.setSuccess(false);
    			ajaxResponse.setMessage("该优惠券已于" + DateFormatUtils.format(dto.getEndDate(), "yyyy-MM-dd")  + "过期，谢谢关注！");
    		}
    		
    		//是否用完
    		List<CouponRedeem> couponRedeemList = couponBatchServiceImpl.getCouponRedeemListByCouponNumber(couponNumber);
    		if(couponRedeemList.size() >=  dto.getMaximunTimes()){
    			ajaxResponse.setSuccess(false);
    			ajaxResponse.setMessage("该优惠券已使用，请核对您输入的券号是否有误！");
    		}
    	}
    	
    	
    	return ajaxResponse;
    }
    
    @RequestMapping(value = "/MARS/coupon")
    public Object couponInfo(WSCrmRedemptionDto wsdto, Model model,
            HttpServletRequest request) throws AppException {
            User user = new User();
            user.setId(0L);
            if(wsdto.getServerCenter()!=null){
                user.setDealerId(Long.valueOf(wsdto.getServerCenter()));
            }
            UserUtil.setMarsCurrentUser(user);
            
            MemberQueryDto dto = new MemberQueryDto();
           /* CarPlateInfo carPlateInfo = maintainCarPlateService.getCarPlateInfoByMarsCarId(wsdto
                .getCarId());
            if (carPlateInfo != null) {
                dto.setCarPlate(carPlateInfo.getCarPlate());
            }*/
            dto.setSoNumber(wsdto.getSoNumber());
            // 根据Mars信息查找到CRM中的会员ID传到前台用于购买操作
            MemberInfo memberInfo = maintainMemberService.getMemberByMarsInfo(wsdto.getServerCenter(),
                wsdto.getCustomerId());
            if (memberInfo != null) {
                dto.setId(memberInfo.getId());
                dto.setDealerId(memberInfo.getDealerId());
                dto.setMemberName(memberInfo.getMemberName());
                dto.setMobilePhone(memberInfo.getMobilePhone());
            }
            
            CarPlateInfo carPlateInfo = maintainCarPlateService.getCarPlateInfoByMarsCarIdAndMemberId(wsdto.getCarId(),
    				memberInfo.getId());
    		if (carPlateInfo != null) {
    			dto.setCarPlate(carPlateInfo.getCarPlate());
    		}
            
            model.addAttribute("carPlateInfo", carPlateInfo);
            model.addAttribute("memberInfo", dto);
            
            return "/mars/coupon";
        }
    
    
	@RequestMapping(value = "/MARS/coupon/ticket/{ticketDefId}")
	public String couponInfo(@PathVariable("ticketDefId") String ticketDefId, Model model, HttpServletRequest request)
			throws AppException {
		List<TicketLine> lineList = ticKetDefineServiceImpl.getTicketLineInfoList(ticketDefId);
		
		Map<Long, Boolean> hasEligibility = new HashMap<Long, Boolean>();

		for (TicketLine ticketLine : lineList) {
			List<Eligibility> list = ticKetDefineServiceImpl.getEligibilityByTicketLineId(ticketLine.getId());

			hasEligibility.put(ticketLine.getId(), list != null && !list.isEmpty());
		}
		
		
		model.addAttribute("lineList", lineList);
		model.addAttribute("hasEligibility", hasEligibility);

		return "/mars/couponLoad";
	}
	
	
	 @RequestMapping(value = "/MARS/toWecareItemTypeInfoList2")
	 public String toWecareItemTypeInfoList2(ItemTypeInfoDto dto,Model model, HttpServletRequest request) throws AppException{
		 
		 int index =1;
	        if(dto.getIndex()!=null){
	            index=dto.getIndex(); 
	        }
	        
	        List<ItemTypeInfoDto> list=redemptionService.getItemListForCoupon(dto);
	        
	        
	        if(dto.getqItemSource() == 0 || dto.getqItemSource() == 1 ){
	        	int i = 0;
	        	for (; i < list.size(); i++) {
					if(!dto.getqItemSource().equals(list.get(i).getItemSource())){
						list.remove(i);
						i--;
					}
				}
	        }
	        
	       
	        PageBean page = new PageBean();  
	        List<ItemTypeInfoDto> listNew= new ArrayList<ItemTypeInfoDto>();  
	        if (list != null &&page!=null) {  
	            for (int i = (index - 1) * page.getPageSize(); i < index * page.getPageSize()  
	                    && i < list.size(); i++) {  
	                listNew.add(list.get(i));  
	            }  
	            page.setPageTotal((list.size() + page.getPageSize() - 1) / page.getPageSize());  
	            page.setRowTotal(list.size());  
	        }  
	        page.setCurrentPage(index);  
	        page.setList(listNew);  
	        
	        
	        model.addAttribute("indexs", index);
	        model.addAttribute("page", page);
	        model.addAttribute("dto", dto);
	        model.addAttribute("itemTypeList", listNew);
	        return "/mars/itemTypeInfoList2";
	    }

}
